package com.htdata.iiot.UpdateMqttPass;

import org.apache.commons.codec.digest.DigestUtils;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.apache.log4j.Logger;

import com.mysql.jdbc.PreparedStatement;

public class UpdataMqttPass {
	public static final int ITERATION_INDEX = 0;
	public static final int SALT_INDEX = 1;
	public static final int PBKDF2_INDEX = 2;

	public static int count = 0;
	public static int successCount = 0;
	private static Logger logger = Logger.getLogger(UpdataMqttPass.class);

	public static PasswordHash pswdHash = new PasswordHash();
	
	
	public static void sha1(String mysqlUrl, String mysqlUser, String mysqlPassword, String mysqlDriver) throws SQLException, ClassNotFoundException {
		
		int all = 0;
		int successAll = 0;
		Connection con;
		Class.forName(mysqlDriver);
		con = (Connection) DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
		if (!con.isClosed())
			logger.info("Succeeded connecting to the Database!");

		Statement statePass = con.createStatement();
		String sqlPass = "SELECT tenant_id,account, password FROM mqtt_user_temp WHERE create_time IN (SELECT "
		                  +"MIN(create_time)FROM mqtt_user_temp GROUP BY tenant_id)";

		String sqlUpdate ="INSERT ignore  INTO mqtt_user(tenant_id,account,passwd) VALUES(?,?,?)";
		int tenantId = 0;
		String account = "";
		String password = "";
		ResultSet rsPass = statePass.executeQuery(sqlPass);
		
		
		while (rsPass.next()) {
			tenantId = rsPass.getInt(1);
			account = rsPass.getString(2);
			password = rsPass.getString(3);
			
			String pas =  DigestUtils.shaHex(password);

			 PreparedStatement ps = (PreparedStatement) con.prepareStatement(sqlUpdate);

			ps.setInt(1, tenantId);
			ps.setString(2, account);
			ps.setString(3, pas);
			
			if (ps.executeUpdate() > 0) {
				successAll++;
			}else{
				System.out.println("sql update fail  tid:"+tenantId+" pass:"+pas+" account"+account);
			}
			all++;
			
		}
		System.out.println(count + "," + successAll);
		rsPass.close();
		statePass.close();
		con.close();
			
	}
	
	public static void work(String mysqlUrl, String mysqlUser, String mysqlPassword, String mysqlDriver) throws SQLException {
		Connection con = null;
		Statement statePass = null;
		ResultSet rsPass    = null;
		try {
			// 加载驱动程序
			Class.forName(mysqlDriver);
			con = (Connection) DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
			if (!con.isClosed())
				logger.info("Succeeded connecting to the Database!");

			statePass = con.createStatement();
			String sqlPass = "select tenant_id,account,password,create_time from user ";
			String sqlInsert ="INSERT INTO mqtt_user_temp(tenant_id,account,password,create_time) values(?,?,?,?)";
		
			int tenantId = 0;
			int usrId = 0;
			int findFlag = 0;
			String account = "";
			String password = "";
			Timestamp time = null;
			String[] pass1 = { "123456qaz", "theta123", "1234qwer", "123456789", "12345678", "123456" };
			int i = 0;
			rsPass = statePass.executeQuery(sqlPass);

			while (rsPass.next()) {
				findFlag = 0;
				tenantId = rsPass.getInt(1);
				account = rsPass.getString(2);
				password = rsPass.getString(3);
				time = rsPass.getTimestamp(4);

				String[] passwords = password.split(":");
				int iterations = Integer.parseInt(passwords[ITERATION_INDEX]);
				String sult = passwords[SALT_INDEX];
				String pbk = passwords[PBKDF2_INDEX];

				for (i = 0; i < pass1.length; i++) {
					if (true == pswdHash.validatePassword(pass1[i], sult, iterations, pbk)) {
						count++;
						findFlag = 1;
						break;
					}
				}
				if(findFlag != 1){
					continue;
				}
				PreparedStatement ps = (PreparedStatement) con.prepareStatement(sqlInsert);
				ps.setInt(1, tenantId);
				ps.setString(2, account);
				ps.setString(3, pass1[i]);
				ps.setTimestamp(4, time);
			
				if (ps.executeUpdate() > 0) {
					successCount++;
				}else{
					System.out.println("sql update fail tid:"+tenantId);
					
				}
			}
			System.out.println(count + "," + successCount);

		} catch (ClassNotFoundException e) {
			logger.error("Sorry,can`t find the Driver!");
			e.printStackTrace();
		} catch (SQLException e) {
			// 数据库连接失败异常处理
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			logger.info("Successful acquisition of database data!");
			rsPass.close();
			statePass.close();
			con.close();
		}

	}

	private static void usage() {
		System.out.println("ags[0]:zookeeper url:port");
	}

	public static void main(String[] args) {
		if (args.length < 1) {
			usage();
			return;
		}

		try {
			ZooKeeperOperator zkoperator = new ZooKeeperOperator();
			zkoperator.connect(args[0]);
			String mysqlUrl = zkoperator.getData("/conf_htiiot/maindb/url");
			String mysqlUser = zkoperator.getData("/conf_htiiot/maindb/user");
			String mysqlPassword = zkoperator.getData("/conf_htiiot/maindb/sec.password");
			String mysqlDriver = zkoperator.getData("/conf_htiiot/maindb/driverclassname");

			work(mysqlUrl, mysqlUser, mysqlPassword, mysqlDriver);
			sha1(mysqlUrl, mysqlUser, mysqlPassword, mysqlDriver);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
